package com.unytech.wisdomcommunity.complainrepairfragment;

import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.unytech.wisdomcommunity.R;
import com.unytech.wisdomcommunity.constant.NetConstant;
import com.unytech.wisdomcommunity.view.ShowPhotoGalleryDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by zed on 2016/11/14/0014.
 * <p/>
 * "投诉"的fragment
 */
public class ComplainFragment extends Fragment implements View.OnClickListener {
    private View mRootView;
    private TextView tv_1, tv_2, tv_cel;
    private Uri imageUri;

    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    public static final int GALLERY = 3;
    private ImageView mAddPhoto_a;
    private ImageView mAddPhoto_b;
    private ImageView mAddPhoto_c;
    private Button mButton_commit;
    //private TextView titleTv;

    private OkHttpClient mClient;

    private static final String TAG = "OKHTTP";
//    private static final String BASE_URL = "http://172.19.161.6:8081/msds/ws/addComplainRepair";
    private EditText mContentET;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.complain_fragment, container, false);
        }
        initView(mRootView);

        initHttp();

        return mRootView;
    }

    //创建okhttp客户端对象
    private void initHttp() {
        mClient = new OkHttpClient();

    }

    private void initView(View mRootView) {

        mAddPhoto_a = (ImageView) mRootView.findViewById(R.id.comlain_addphoto_iv_a1);
        mAddPhoto_b = (ImageView) mRootView.findViewById(R.id.comlain_addphoto_iv_b1);
        mAddPhoto_c = (ImageView) mRootView.findViewById(R.id.comlain_addphoto_iv_c1);
        mButton_commit = (Button) mRootView.findViewById(R.id.complain_repair_commit_btn);
        //中间那个编辑框
        mContentET = ((EditText) mRootView.findViewById(R.id.comlain_repair_et_1));
        //提交按钮
        mButton_commit.setOnClickListener(this);

        mAddPhoto_a.setOnClickListener(this);
        mAddPhoto_b.setOnClickListener(this);
        mAddPhoto_c.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.comlain_addphoto_iv_a1:
                //弹出popupWindow
                //showPopupWindow(v);
                //2.弹出Dialog
                initDialog();
                break;
            case R.id.comlain_addphoto_iv_b1:
                break;
            case R.id.comlain_addphoto_iv_c1:
                break;
            case R.id.complain_repair_commit_btn:
                //非空判断
                if (TextUtils.isEmpty(mContentET.getText())) {
                    Toast.makeText(getActivity(), "请编辑完善之后再提交哦~", Toast.LENGTH_SHORT).show();
                } else {
                    Log.d(TAG, "onClick: " + "点击  事件  走了");
                    //1.设置参数
                    RequestBody body = new FormBody.Builder()
                            .add("complainRepair","{\"content\":\"sdf\",\"userId\":20},\"imgPath\":\"sdf\",\"repairId\":3}")
//                            .add("content", "1234" + mContentET.getText())//给post添加请求头
                            //.add("image","d://1.png")
//                            .add("repairId", "2")
                            .build();
                    //2.封装请求
                    Request request = new Request.Builder()
                            .url(NetConstant.BASE_URL+NetConstant.ADD_COMPLAINREPAIR)
                            .post(body)
                            .build();
                    Log.d(TAG, "onClick: "+ request.url());
                    //3.发送请求
                    mClient.newCall(request)
                            .enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.i(TAG, "onFailure: 服务器连接有问题" + e);
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            int code = response.code();

                            Log.d(TAG, "onResponse: 响应码" + code);
                            String data = response.body().string();
                            Log.i(TAG, "onResponse: " + data);

                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    //2.初始化Dialog
    private void initDialog() {
        ShowPhotoGalleryDialog dialog = new ShowPhotoGalleryDialog(getActivity(), this);
        dialog.show();
    }

    private void showPopupWindow(View v) {
        View pupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_window_layout, null);

        tv_1 = ((TextView) pupView.findViewById(R.id.pop_tv_1));
        tv_2 = ((TextView) pupView.findViewById(R.id.pop_tv_2));
        tv_cel = ((TextView) pupView.findViewById(R.id.pop_tv_cel));

        //点击开启  手机的摄像头
        tv_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day_of_month = calendar.get(Calendar.DAY_OF_MONTH);
                int hour_of_day = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                int second = calendar.get(Calendar.SECOND);
                //用年月日时分秒来命名拍摄照片
                File imageFile = new File(Environment.getExternalStorageDirectory(),
                        year + month + day_of_month + hour_of_day + minute + second + ".jpg");

                try {
                    if (imageFile.exists()) {
                        imageFile.delete();
                    }
                    imageFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imageUri = Uri.fromFile(imageFile);

                Toast.makeText(getActivity(), "点击了拍照", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, TAKE_PHOTO);//点击开启手机相机程序
            }
        });
        final PopupWindow popupWindow = new PopupWindow(pupView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        //把事件拦截下来
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        // 设置好参数之后再show
        //popupWindow.showAsDropDown(v);
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

        tv_cel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == getActivity().RESULT_OK) {
                    Intent cropIntent = new Intent("com.android.camera.action.CROP");

                    cropIntent.setDataAndType(imageUri, "image/*");
                    cropIntent.putExtra("scale", true);
                    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                    startActivityForResult(cropIntent, CROP_PHOTO);
                }
                break;
            case CROP_PHOTO:
                if (resultCode == getActivity().RESULT_OK) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
                        mAddPhoto_a.setImageBitmap(bitmap); // 将裁剪后的照片显示出来
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
                /*case GALLERY:
                    if (resultCode == RESULT_OK){
                        Intent cropIntent = new Intent("com.android.camera.action.CROP");

                        Toast.makeText(getApplicationContext(),"相册打开了",Toast.LENGTH_SHORT).show();

                        cropIntent.setDataAndType(imageUri, "outimage*//*");
                        cropIntent.putExtra("scale", true);
                        cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                        startActivityForResult(cropIntent,CROP_PHOTO);
                    }
                    break;*/
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /*if (){

        }*/
    }

/*
    public static void main(String[] args){
        String encode = null;
        try {
            encode = URLEncoder.encode("{\"userId\":20,\"content\":\"在在\",\"repairId\":2,\"imagePath\":\"sss\"}","utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 设置get请求参数的方式
*/
/*
        Uri uri = Uri.parse(NetConstant.BASE_URL).buildUpon()
                .appendPath("msds/ws/getComplainRepair")   // 拼接路径, 路径开头不要有斜杠
                .appendQueryParameter("pageNo", "1")
                .appendQueryParameter("pageSize", "15")
                .build();
*//*

        // 1. 封装请求
        Request request = new Request.Builder()
                .url(NetConstant.BASE_URL + "/msds/ws/getComplainRepair?complainRepair={\"userId\":20}&pageNo=1&pageSize=15")   // url后面直接拼接参数
                //.url(uri.toString())
                // .addHeader("userid", "")   // 加请求头
                .get()
                .build();

        // 2. 发送请求
        OkHttpClient mClient = new OkHttpClient();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.i(TAG, "onFailure: "+e);
                System.out.println("onFailure" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                //Log.d(TAG, "onResponse: 响应码"+ code );
                String data = response.body().string();

                System.out.println("响应码"+code+"data"+data);
            }
        });
    }
*/

    /*{
        System.out.print("11");
        //String urlParam = "{\"userId\":20,\"content\":\"在在\",\"repairId\":2,\"imagePath\":\"sss\"}";

        String encode = null;
        try {
            encode = URLEncoder.encode("{\"userId\":20,\"content\":\"在在\",\"repairId\":2,\"imagePath\":\"sss\"}","utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        RequestBody body = new FormBody.Builder()
                .add("complainRepair",encode)
//                            .add("content", "1234" + mContentET.getText())//给post添加请求头
                //.add("image","d://1.png")
//                            .add("repairId", "2")
                .build();

//        complainRepair={"userId":30, "content": "在在", "repairId": 2, "imagePath": "sss"}

        //2.封装请求
        Request request = new Request.Builder()
                .url(NetConstant.BASE_URL+"/msds/ws/addComplainRepair")
                .post(body)
                .build();
        System.out.println(NetConstant.BASE_URL+request.body() + "|" +encode);
        OkHttpClient mClient = new OkHttpClient();
        mClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.print("服务器连接有问题"+e.getMessage());
//                        Log.i(TAG, "onFailure: 服务器连接有问题" + e);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        int code = response.code();

//                        Log.d(TAG, "onResponse: 响应码" + code);
                        System.out.print("响应码"+code);
                        String data = response.body().string();
                        System.out.print("onResponse"+data);
//                        Log.i(TAG, "onResponse: " + data);

                    }
                });
    }*/
}